<?php

namespace app\api\controller;

use think\Controller;
use think\Db;
use think\image\Exception;

class Purchase extends Base {

    protected $user;

    /*************************************************************************
     * 接口方法
     *************************************************************************/

    /**
     * 确认订单
     * @return json
     */
    public function firmOrder() {
            $data = request()->post();
            if (array_key_exists('sign',$data)){
                unset($data['sign']);
            }
            if(isset($data['type']) && $data['type'] == 'APP'){
                $data['goods'] = json_decode($data['goods'],true);
                file_put_contents('text.txt',json_encode($data));
            }
            $supplier = $data['goods'];
            $user = Db::name('user')->where('id',$data['user_id'])->find();
            $set  = Db::name('system_setting')->where('id',1)->find();
            Db::startTrans();
            $isCheck = true;
            try {
                foreach ($supplier as $k => $v) {
                    $order = [];
                    $order['order_no']      = createOrderNo();
                    $order['supplier_id']   = $v['supplier_id'];
                    $order['remark']        = $v['remark'];
                    $order['status']        = 1;
                    $order['user_id']       = $data['user_id'];
                    $order['add_time']      = date('Y-m-d H:i:s');
                    $order['addr']          = $user['addr'];
                    $order['send_time']     = self::getSendDate($user['city'], $user['town'], $v['supplier_id']);
                    if ('00:00:00' == $order['send_time']){
                        $result['status'] = 202;
                        $result['msg'] = '该商家暂无配送日程!/The merchant has no delivery';
                        $isCheck = false;
                        break;
                    }
                    $order_id = Db::name('order')->insertGetId($order);
//                    $order_id = Db::name('order')->getLastInsID();
                    $money = 0;
                    $tax = 0;
                    $relief_money = 0;
                    foreach ($v['product'] as $key => $val) {
                        $order_info = [];
                        $order_info['order_id']             = $order_id;
                        $order_info['product_id']           = $val['product_id'];
                        $order_info['num']                  = $val['num'];
                        $order_info['price']                = (Float)$val['price'];
                        $order_info['specification_name']   = $val['packing_proportion'].$val['unit'];
                        $order_info['packing_proportion']   = $val['packing_proportion'];
                        $order_info['unit']                 = $val['unit'];
                        if ($val['is_include_tax'] == 0) {
                            $order_info['tax'] = $set['value'] * $val['num'] * (Float)$val['price'];
                            $tax    += $order_info['tax'];
                            $money  += $order_info['tax'];
                        } else {
                            $order_info['tax'] = 0;
                        }
                        $product_money  = $order_info['num'] * $order_info['price'];
                        $money          += $product_money;
                        $discount       = self::setDiscount($order_info['num'], $val['product_id']);
                        if (!empty($discount)) {
                            if ($discount['type'] == 1) {
                                $relief_money += $discount['data'];
                            } elseif ($discount['type'] == 2) {
                                $order_info['step']         = $discount['step'];
                                $order_info['give_product'] = $discount['data'];
                            }
                        }
                        Db::name('order_info')->insert($order_info);
                    }
                    $minimum = Db::table('supplier')->where('id', $v['supplier_id'])->value('minimum');
                    $minimum = number_format($minimum, 2, '.', '');
                    if ($relief_money > 0) {
                        $paymoney = $money - $relief_money;
                        if ($paymoney <= 0) {
                            $paymoney = 0;
                        }
                        if ($money < $minimum) {
                            $result['status'] = 209;
                            $result['msg'] = $v['supplier_name'] . '最低消费 ￡' . $minimum;
                            $result['money'] = $money;
                            $isCheck = false;
                            break;
//                            return json($result);
                        } else {
                            $ok = Db::name('order')->where('id', $order_id)->update(['money' => $money, 'tax' => $tax, 'discountmoney' => $relief_money, 'paymoney' => $paymoney]);
                        }
                    } else {
                        if ($money < $minimum) {
                            $result['status'] = 209;
                            $result['msg'] = $v['supplier_name'] . '最低消费 ￡' . $minimum;
                            $result['money'] = $money;
                            $isCheck = false;
                            break;
//                            return json($result);
                        } else {
                            $ok = Db::name('order')->where('id', $order_id)->update(['money' => $money, 'tax' => $tax, 'paymoney' => $money]);
                        }
                    }

                    if ($ok) {
                        $result['status'] = 200;
                        $result['msg'] = '创建订单成功';
                        $result['money'] = $money;
                    } else {
                        $result = config('code.error');
                        $isCheck = false;
                        break;
                    }
                    /*if(empty($discount)){
                        //商家无活动
                        $ok = Db::name('order')->where('id',$order_id)->update(['money'=>$money,'tax'=>$tax,'paymoney'=>$money]);
                    }else{
                        //商家有活动,插入活动数据
                        Db::name('order')->where('id',$order_id)->update(['money'=>$money,'tax'=>$tax]);
                        $ok = self::insertDiscountData($discount,$money,$order_id);
                    }*/
                }
                if($isCheck) {
                    Db::commit();
                }
//                return json($result);
            }catch (Exception $e){
                $result = config('code.error');
            }
            return json($result);
    }

    /**
     * 购货(搜索)
     * @return json
     * data:total 用于显示总数 app做下拉显示可
     */

    public function buyProduct() {
        try {
            $cateId  = input('cate_id', 0, 'intval'); //分类id
            $typeId  = input('type_id', 0, 'intval'); //种类id
            $brandId = input('brand_id', 0, 'intval'); //品牌id
            $smallTypeId = input('small_type_id',0,'intval');//小类id
            $spc    = input('num');//规格
            $total  = input('total', 6, 'intval'); //分页数
            $num    = input('num', 1); //购买数量
            //设置搜索条,
            $where = self::getWhere($cateId, $typeId, $brandId, $num,$smallTypeId,$spc);
//            var_dump($where);exit;
            //根据搜索条件搜索列表数据
            $list = self::getProductList($where,$total);
            //分页对象转换数组
            $arr = $list->toArray();
            //获取含税率
            $tag = db::name('system_setting')->find();
            $data = $arr['data'];
            $time  = date("Y-m-d H:i:s", time());
            foreach ($data as $k=>$v){
                $where  = [
                    'product_id'          => $v['product_id'],
                    'status'              => 1,
                    'start_time'          => ['<=',$time],
                    'end_time'            => ['>=',$time]
                ];
                $count = Db::table('discount')
                    ->where($where)
                    ->count();
                if ($count>0){
                    $data[$k]['is_discount'] = 1;
                }else{
                    $data[$k]['is_discount'] = 0;
                }
            }
            $result['html'] = $list->render();
            $result['total'] = $arr['total'];
            $result['current_page'] = $arr['current_page'];
            $result['last_page'] = $arr['last_page'];
            $result['tax'] = $tag['value'];
            //将商品分配给自己所在的商家
            $result['data'] = self::getProductSupplier($data);
            $res = config('code.success');
            $res['data'] = $result;
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = $ex->getMessage();
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * 获取分类
     * @return json
     */
    public function getClass() {
        $id = input('pId',1,'intval');
        try {
            $data = Db::name('base_data')->where(['parent_id'=>$id,'flag'=>1])->select();
            $arr = [];
            foreach ($data as $value){
                $list = Db::name('base_data')->where(['parent_id'=>$value['id'],'flag'=>1])->select();
                $value['list'] = $list;
                $arr[] = $value;
            }
            $res = config('code.success');
            $res['list'] = $arr;
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['list']);
    }

    /**
     * 种类选择列表数据
     * @return json
     */
    public function classify() {
        try {
            $status = input('status', 1, 'intval');
            //分类数据
            $cate = self::getBaseData('a.category_id=b.id', $status);
            //种类数据
            $type = self::getBaseData('a.type_id=b.id', $status);
            //品牌数据
            $brand = self::getBaseData('a.brand_id=b.id', $status);
            $data['category'] = $cate;
            $data['type'] = $type;
            $data['brand'] = $brand;
            $res = config('code.success');
            $res['data'] = $data;
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * 历史报价单
     * @return json
     */
    public function historyList() {
        try {
            $user = self::isLogin();
            //用户订单信息
            $orders = self::getOrderListByUserId($user['id']);
            $arr = $orders->toArray();
            $order = $arr['data'];
            $res['html'] = $orders->render();
            $res['current_page'] = $arr['current_page'];
            $res['last_page'] = $arr['last_page'];
            $res['total'] = $arr['total'];
            //用户订单商品信息
            $goods = self::getGoodsListByUserId($user['id']);
            //将商品归入所属订单
            $list = self::getOrderHistory($order, $goods);
            if(!empty($order)) {
                $res = config('code.success');
                $res['data'] = $list;
            }else{
                $res['status'] = 202;
                $res['msg']    = '暂无数据';
            }
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = $ex->getMessage();
        }
        return json($res);
    }
    
    /**
     * 历史报价单
     * @return json
     */
    public function historyListWeb() {
        try {
            $user = self::isLogin();

            $cateId = input('cate_id', 0, 'intval'); //分类id
            $typeId = input('type_id', 0, 'intval'); //种类id
            $brandId = input('brand_id', 0, 'intval'); //品牌id
            $smallTypeId = input('small_type_id',0,'intval');//小类id
            $total = input('total', 5, 'intval'); //每页显示数
            $num = input('num', 0, 'intval'); //库存
            $where = self::setWhere($cateId, $typeId, $brandId,$smallTypeId,$num);
            if(0 >= $total){
                $total = 5;
            }
            //用户订单信息
            $orders = self::getWebOrderListByUserId($user['id'],$where,$total);

            $arr = $orders->toArray();
            $order = $arr['data'];

            //用户订单商品信息
            $goods = self::getGoodsListByUserId($user['id'],$where);
            //将商品归入所属订单
            $list = self::getOrderHistory($order, $goods);
            //获取含税率
            $tag = db::name('system_setting')->find();
            $res = config('code.success');
            $res['tax'] = $tag['value'];
            $res['data'] = $list;
            $res['html'] = $orders->render();
            $res['current_page'] = $arr['current_page'];
            $res['last_page'] = $arr['last_page'];
            $res['total'] = $arr['total'];
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = $ex->getMessage();
        }
        return json($res);
    }

    /**
     * 购货车(编辑)
     * @return type
     */
    public function shoppingCart() {
        try {
            $productId = input('product_id', 0, 'intval');
            $list = Db::name('product_specification')->where(['product_id' => $productId])->select();
            $res = config('code.success');
            $res['data'] = $list;
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-04-10T17:45:06+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:加入购物车
     * @param:
     */
    public function shoppingCartInsert(){
        $data = request()->post();
        if(empty($data['user_id'])|| empty($data['product_id'])|| empty($data['product_specif_id'])|| empty($data['supplier_id'])|| empty($data['num'])){
            return json(config('code.miss'));
        }
        $num = $data['num'];
        unset($data['sign']);
        unset($data['num']);
        if($data['cart_id']!==''){
            $cart_id= $data['cart_id'];
            $sid    = $data['product_specif_id'];
            unset($data['cart_id']);
            unset($data['product_specif_id']);
            $Re = Db::name('order_user_cart')->where('id',$cart_id)->find();
            if($Re){
                $save['num'] = $num;
                $save['product_specif_id'] = $sid;
                Db::name('order_user_cart')->where('id',$cart_id)->update($save);
                $id = $cart_id;
            }else{
                $data['num'] = $num;
                $data['product_specif_id'] = $sid;
                $id = Db::name('order_user_cart')->insertGetId($data);
            }
        }else{
            unset($data['cart_id']);
            $Re = Db::name('order_user_cart')->where($data)->find();
            if($Re){
                Db::name('order_user_cart')->where($data)->setInc('num',$num);
                $id = $Re['id'];
            }else{
                $data['num'] = $num;
                $id = Db::name('order_user_cart')->insertGetId($data);
            }
        }
        $result = config('code.success');
        $result['id'] = $id;
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-04-10T17:45:06+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:条件删除购物车数据
     * @param:
     */
    public function delCart(){
        $data = request()->post();
        if( empty($data['user_id']) || empty($data['delStr']) ){
            return json(config('code.miss'));
        }
        $where['user_id'] = $data['user_id'];
        $data['delStr']   = trim($data['delStr'],',');
        $arr = explode(',', $data['delStr']); 
        $where['supplier_id'] = array('in',$arr);
        $Re = Db::name('order_user_cart')->where($where)->delete();
        if($Re){
            $result = config('code.success');
        }else{
            $result = config('code.error');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-04-18
     * @rewriter:xx
     * @rewriter_date:
     * @description:   购货车列表
     * @param:[]
     * @return[$result]
     */
    public function cartList(){
        $post = request()->post();
        if (!empty($post['user_id'])){
            $data = Db::table('order_user_cart')
                ->alias('c')
                ->field('s.id as supplier_id, s.is_open, s.name as supplier_name, s.image, s.minimum, s.send_time_type, 
                u.addr as address, u.phone as tel, u.city, u.town')
                ->join('supplier s','c.supplier_id = s.id')
                ->join('user u','c.user_id = u.id')
                ->where('user_id',$post['user_id'])
                ->group('c.supplier_id')
                ->select();
            $tax = Db::table('system_setting')->where('name','增值税比例')->value('value');
            $send_date  =   '暂无配送';
            foreach ($data as $k=>$v){
                if ($v['send_time_type'] == 1){                  //周配送.
                    $send = Db::table('supplier_send_manage')
                        ->field('day, month, send_area')
                        ->where(['supplier_id'=>$v['supplier_id']])
                        ->where('month',0)
                        ->order('day desc')
                        ->select();
                    $before_now = [];
                    $after_now = [];
                    $time = timeCompute(time());
                    $week = date('w');
                    foreach ($send as $kk=>$vv){
                        if ($vv['send_area'] == $v['city'] || $vv['send_area'] == $v['town']){
                            if ($vv['day'] < $week){
                                $before_now[] = $vv['day'];
                            }else{
                                $after_now[] = $vv['day'];
                            }
                        }
                    }
					

                    if ($after_now){
                        $time1 = (min($after_now) - $week)*24*60*60;
                        $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                        $send_date = date("Y-m-d", $date);
                    }else if($before_now){
                        $time1 = ( 7-($week-min($before_now)))*24*60*60;
                        $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                        $send_date = date("Y/m/d", $date);
                    }
                }elseif ($v['send_time_type'] == 2){           //月配送.
                    $send = Db::table('supplier_send_manage')
                        ->field('day, month, send_area')
                        ->where(['supplier_id'=>$v['supplier_id']])
                        ->where('month','<>',0)
                        ->select();
                    foreach ($send as $kk=>$vv){
                        $time = timeCompute(time());
                        if ($vv['month']<$time['month'] || ($vv['month']==$time['month'] && $vv['day'] < $time['day'])){
                            $send_date  =   '暂无配送';
                        }else{
                            if ($vv['send_area'] == $v['city'] || $vv['send_area'] == $v['town']){
                                $send_date = $time['year'].'/'.$vv['month'].'/'.$vv['day'];
                            }
                        }
                    }
                }
                $data[$k]['date']  = $send_date;
                $data[$k]['minimum']    = number_format($v['minimum'],2,'.','');
                $data[$k]['totalTax']   = 0;
                $data[$k]['totalMoney'] = 0;
                $totalTax   = 0;
                $totalMoney = 0;
                $product = Db::table('order_user_cart')
                    ->alias('c')
                    ->field('c.id as user_cart_id, c.product_specif_id as sid, c.product_id, c.num, ps.packing_proportion, ps.specification, ps.price, ps.unit,
                    p.is_shelves, p.name as product_name, p.image as product_image, p.stock, p.is_include_tax')
                    ->join('product p','c.product_id = p.id')
                    ->join('product_specification ps','c.product_specif_id = ps.id')
                    ->where('user_id',$post['user_id'])
                    ->where('supplier_id',$v['supplier_id'])
                    ->select();
                $goods = [];
                foreach ($product as $kk=>$vv){
                    if ($vv['is_include_tax'] == 0){
                        $product[$kk]['tax'] = (float)$tax * (float)$vv['price'];
                    }else{
                        $product[$kk]['tax'] = 0;
                    }
                    $total_price    = (float)$vv['price']            * (float)$vv['num'] * (float)$vv['specification'];
                    $total_tax      = (float)$product[$kk]['tax']    * (float)$vv['num'] * (float)$vv['specification'];
                    $total_money    = $total_price + $total_tax;
                    $product[$kk]['price']       = number_format($product[$kk]['price'],2,'.','');
                    $product[$kk]['total_tax']   = number_format($total_tax,2,'.','');
                    $product[$kk]['total_price'] = number_format($total_money,2,'.','');
                    $discount = $this->discount($vv['product_id']);
                    if ($discount){
                        $product[$kk]['is_discount']        = 1;
                        $product[$kk]['discount_type']      = $discount['type'];
                        $product[$kk]['condition_money']    = $discount['condition_money'];
                        $product[$kk]['discount_money']     = $discount['relief_money'];
                        $product[$kk]['give_product']       = $discount['give_product'];
                        $product[$kk]['discount_type']      = $discount['type'];
                        if ($discount['condition_money']>0){
                            $much = floor($product[$kk]['total_price']/$discount['condition_money']);   //倍数
                            $product[$kk]['much'] = $much;
                            if ($discount['type'] == 1){        //满减
                                $discount_money = $much * $discount['relief_money'];
                                $pay_price      = $total_money - $discount_money;
                                $product[$kk]['discount']       = '￡'.number_format($discount_money,2,'.','');;
                                $product[$kk]['total_price']    = number_format($pay_price,2,'.','');
                            }
                            if ($discount['type'] == 2){        //满送
                                $product[$kk]['discount'] = $product[$kk]['give_product'].'*'.$much;
                            }
                        }
                    }else{
                        $product[$kk]['is_discount']    = 0;
                        $product[$kk]['discount']       = '--';
                    }
                    if (!empty($post['ids'])){
                        foreach ($post['ids'] as $value){
                            if ($vv['cart_id'] == (int)($value)){
                                $totalTax   += number_format($product[$kk]['total_tax'],2,'.','');
                                $totalMoney += number_format($product[$kk]['total_price'],2,'.','');
                                $data[$k]['totalTax']   = number_format($totalTax,2,'.','');
                                $data[$k]['totalMoney'] = number_format($totalMoney,2,'.','');
                                $goods[] = $product[$kk];
                            }
                        }
                    }else{
                        $totalTax   += number_format($product[$kk]['total_tax'],2,'.','');
                        $totalMoney += number_format($product[$kk]['total_price'],2,'.','');
                        $data[$k]['totalTax']   = number_format($totalTax,2,'.','');
                        $data[$k]['totalMoney'] = number_format($totalMoney,2,'.','');
                    }
                }
                if (!empty($goods)){
                    $data[$k]['product'] = $goods;
                }else{
                    $data[$k]['product'] = $product;
                }
            }
            $result = config('code.success');
            $result['buy_car'] = $data;
        }else{
            $result = config('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-04-18
     * @rewriter:xx
     * @rewriter_date:
     * @description: 优惠活动
     * @param:[]
     * @return[$result]
     */
    private function discount($product_id){
        $discount_info = Db::table('discount')
            ->field('id, type, condition_money, ifNull(relief_money,0) as relief_money, give_product, start_time, end_time')
            ->where(['product_id'=>$product_id, 'status'=>1])
            ->find();
        $re = [];
        if ($discount_info){
            $time       = strtotime("now");
            $start_time = strtotime($discount_info['start_time']);
            $end_time   = strtotime($discount_info['end_time']);
            if ($start_time <= $time && $time <= $end_time){
                $re = $discount_info;
            }
        }
        return $re;
    }























    /***************************************************************************
     * 操作方法
     ***************************************************************************/

    /**
     * 获取搜索商品列表数据
     * @param type $where
     * @return type
     */
    protected static function getProductList($where,$total) {

        return Db::name('product')->alias('a')
                ->join('base_data b', 'a.category_id=b.id', 'left')
                ->join('base_data c', 'a.type_id=c.id', 'left')
                ->join('base_data d', 'a.brand_id=d.id', 'left')
                ->join('product_specification e', 'a.id=e.product_id', 'left')
                ->join('supplier f','a.supplier=f.id','left')
                ->where($where)
                ->where('f.check_status',2)
                ->where('f.is_open',1)
                ->where('a.status',1)
                ->where('a.is_shelves',1)
                ->group('a.id')
                ->field('a.name as product_name,'
                        . 'a.id as product_id,e.packing_proportion,e.unit,e.specification,format(e.price,2) as price,a.is_include_tax,'
                        . 'f.image as supplier_image,f.name as supplier_name,'
                        . 'f.id as supplier,a.image as product_image')
                ->paginate($total,FALSE,['path'=>'javascript:AjaxPage([PAGE]);','type'=> 'BootstrapDetailed']);
    }


    public function getSendDate($city,$twon,$supplier_id){
        $supplier = Db::name('supplier')->field('send_time_type')->where('id',$supplier_id)->find();
        $re = Db::name('supplier_send_manage')
            ->where('supplier_id',$supplier_id)
            ->where('flag',1)
            ->where('send_area',$city)
            ->whereOr('send_area',$twon)
            ->order('day asc')
            ->select();
        $day = date('d');
        $y = date('Y');
        $m = date('m');
        $d = date('d');

        if($supplier['send_time_type'] ==1){                // 周配送
            $week = date('w');
            if(count($re) == 1){
                if($week < $re[0]['day']){
                    $time = ($re[0]['day'] - $week)*24*60*60;
                    $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                }else{
                    $time = ( 7-($week-$re[0]['day']))*24*60*60;
                    $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                }
            }else{
                $is_choose = false;
                foreach ($re as $k => $item) {
                    if ($item['day'] > $day) {
                        $time = ($re[$k]['day'] - $week)*24*60*60;
                        $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                        $is_choose = true;
                        break;
                    }
                }
                if(!$is_choose){
                    if(count($re) == 0){
                        $date = '暂无配送信息';
                    }else {
                        $time = (7 - ($week - $re[0]['day'])) * 24 * 60 * 60;
                        $date = strtotime($y . '-' . $m . '-' . $d . ' 00:00:00') + $time;
                    }
                }
            }

        }else{                                      // 月配送
            if(count($re) == 1){
                if($day> $re[0]['day']){
                    $date = strtotime($y.'-'.($m+1).'-'.$re[0]['day'].' 00:00:00');
                }else{
                    $date = strtotime($y.'-'.$m.'-'.$re[0]['day'].' 00:00:00');
                }
            }else {
                $is_choose = false;
                foreach ($re as $k => $item) {
                    if ($item['day'] > $day) {
                        $date = strtotime($y.'-'.$m.'-'.$re[$k]['day'].' 00:00:00');
                        $is_choose = true;
                        break;
                    }
                }
                if(!$is_choose){
                    if(count($re) == 0){
                        $date = '暂无配送信息';
                    }else {
                        $date = strtotime($y . '-' . ($m + 1) . '-' . $re[0]['day'] . ' 00:00:00');
                    }
                }
            }
        }
        if($date != '暂无配送信息') {
            return date('Y-m-d H:i:s', $date);
        }else{
            $date = '00:00:00';
            return $date;
        }
//        return date('Y-m-d H:i:s',$date);
    }
    /**
     * 商品数据归类
     * @param array $arr
     * @return array
     */
    protected static function getProductSupplier($arr){
        $ids = $res = [];
        foreach ($arr as $k=>$v){
            if(!in_array($v['supplier'], $ids)){
                $ids[] = $v['supplier'];
            }
        }
        foreach ($ids as $key=>$id){
           foreach ($arr as $val){
                if($id == $val['supplier']){
                    $res[$key]['supplier_name'] = $val['supplier_name'];
                    $res[$key]['supplier_id'] = $val['supplier'];
                    $res[$key]['supplier_image'] = $val['supplier_image'];
                    unset($val['supplier_name']);
                    unset($val['supplier']);
                    unset($val['supplier_image']);
                    $res[$key]['goods'][] = $val;
                }
            }
        }
        return $res;
    }

    /**
     * 历史报价单列表
     * @param array $order
     * @param array $goods
     * @return array
     */
    protected static function getOrderHistory($order, $goods) {
        $arr = [];
        foreach ($order as $key => $val) {
            $count = 0;
            foreach ($goods as $k => $v) {
                if ($val['id'] == $v['order_id']) {
                    $arr[$key]['id'] = $val['id'];
                    $arr[$key]['money'] = $val['money'];
                    $arr[$key]['info']['supplier_id'] = $v['supplier_id'];
                    $arr[$key]['info']['supplier_name'] = $v['supplier_name'];
                    $arr[$key]['order_tax'] = $v['order_tax'];
                    $arr[$key]['total'] = $v['money'];
                    $arr[$key]['info']['image'] = $v['image'];
                    $count += $v['packing_proportion'];
                    unset($v['supplier_id']);
                    unset($v['supplier_name']);
//                    unset($v['num']);
                    unset($v['image']);
                    unset($v['order_id']);
                    $arr[$key]['info']['goods'][] = $v;
                }
            }
            $arr[$key]['count'] = $count;
            if(0 == $count){
                unset($arr[$key]);
            }
        }
        unset($order);
        unset($goods);
        return $arr;
    }

    /**
     * 根据用户id获取用户的订单
     * @param int $id
     * @return object
     */
    protected static function getOrderListByUserId($id,$total=5) {
        return Db::name('order')->alias('a')
                ->join('supplier d', 'a.supplier_id=d.id', 'left')
                ->field('a.*,d.name as supplier_name')
                ->where(['a.user_id' => $id])
               ->paginate($total,FALSE,['path'=>'javascript:AjaxPage([PAGE]);','type'=> 'BootstrapDetailed']);
    }
    
    /**
     * 设置活动数据
     * @param float $money
     * @param int $id
     * @return array
     */
    protected static function setDiscount($num,$id){
        $where['product_id']    = $id;
        $where['start_time']    = ['<', date('Y-m-d H:i:s')];
        $where['end_time']      = ['>', date('Y-m-d H:i:s')];
        $where['status']        = 1;
        $discount = Db::name('discount')->where($where)->find();
        if(!$discount['type']){
            $res = [];
        }else{
            if ($discount['condition_num']>0){
                $step = floor($num/$discount['condition_num']);
                switch ($discount['type']){
                    case 1:
                        $discountMoney = $discount['relief_money']*$step;
                        $res['type'] = 1;
                        $res['step'] = $step;
                        $res['data'] = $discountMoney;
//                        $res = self::discountMoney($step,$discount['relief_money']);
                        break;
                    case 2:
                        $res['type'] = 2;
                        $res['step'] = $step;
                        $res['data'] = $discount['give_product'];
//                        $res = self::discountGive($step,$discount['id']);
                        break;
                }
            }else{
                $res = [];
            }
        }
        return $res;
    }
    
    /**
     * 满减金额计算
     * @param float $money
     * @param float $rule
     * @param float $relief
     * @return array
     */
    protected static function discountMoney($step,$relief){
        $discountMoney = $relief*$step;
        $res['type'] = 1;
        $res['data'] = $discountMoney;
        return $res;
    }
    
    /**
     * 满送活动计算
     * @param int $step
     * @param int $id
     * @return array
     */
    protected static function discountGive($step,$id){
        $product = Db::name('product_give')->alias('a')
                ->join('product b','a.product_id=b.id','left')
                ->field('a.count,b.*')
                ->where(['a.discount_id'=>$id])
                ->find();
        if(!$product){
            $res = [];
        }else{
            $product['count'] *= $step;
            $res['type'] = 2;
            $res['data'] = $product;
        }
        return $res;
    }
    
    /**
     * 设置折扣数据
     * @param array $data
     * @param float $money
     * @param int $id
     * @return boolbean
     */
    protected static function insertDiscountData($data,$money,$id){
        switch ($data['type']){
            //满减
            case 1:
                $insert['discountmoney'] = $data['data'];
                $insert['paymoney'] = $money - $data['data'];
                $ok = Db::name('order')->where(['id'=>$id])->update($insert);
                break;
            case 2:
                Db::name('order')->where('id',$id)->update(['paymoney'=>$money]);
                $insert['order_id']     = $id;
                $insert['product_id']   = $data['data']['id'];
                $insert['num']          = $data['data']['count'];
                $insert['price']        = 0;
                $insert['tax']          = 0;
                $insert['is_give']      = 1;
                $insert['specification_name']   = 1;
                $insert['packing_proportion']  = $data['data']['count'];
                $ok = Db::name('order_info')->insertGetId($insert);
                break;
        }
        return $ok;
    }

    /**
     * 根据用户id获取用户的订单
     * @param int $id
     * @return object
     */
    protected static function getWebOrderListByUserId($id,$where,$total) {
        return Db::name('order')->alias('a')
                ->join('order_info c','a.id=c.order_id','left')
                ->join('product b','c.product_id=b.id','left')
                ->join('supplier d', 'a.supplier_id=d.id', 'left')
                ->field('a.*,d.name as supplier_name,b.is_include_tax')
                ->where(['a.user_id' => $id])
                ->where(['a.status'=>['neq',6]])
                ->where($where)
                ->group('a.id')
                ->paginate($total,FALSE,['path'=>'javascript:AjaxPage([PAGE]);','type'=> 'BootstrapDetailed']);
    }
    /**
     * 根据用户id获取订单商品信息
     * @param int $id
     * @return array
     */
    protected static function getGoodsListByUserId($id) {
        return Db::name('order_info')->alias('a')
                ->join('product b', 'a.product_id=b.id', 'left')
                ->join('product_specification c', 'b.id=c.product_id', 'left')
                ->join('supplier e','b.supplier=e.id','left')
                ->join('order d', 'a.order_id=d.id', 'left')
                ->field('a.*,b.name as product_name,b.is_include_tax,d.tax as order_tax,d.money,'
                        . 'e.id as supplier_id,e.name as supplier_name,'
                        . 'e.image,b.image as product_image')
                ->where(['d.user_id' => $id])
                ->group('a.id')
                ->select();
    }

    /**
     * 商品关联基础数据获取信息
     * @param string $str
     * @param int $status
     * @return array
     */
    protected static function getBaseData($str, $status) {
        return Db::name('product')->alias('a')
                ->join('base_data b', $str, 'left')
                ->field('b.id,b.name,b.name_english')
                ->where(['a.status' => $status])
                ->select();
    }

    /**
     * 组装产品搜索查询条件
     * @param int $cateId
     * @param int $typeId
     * @param int $brandId
     * @param int $num
     * @param int $smallTypeId
     * @return array
     */
    protected static function getWhere($cateId, $typeId, $brandId, $num,$smallTypeId,$spc) {
        $where = [];
        if (!empty($cateId)) {
            $where['a.category_id'] = $cateId;
        }
        if (!empty($typeId)) {
            $where['a.type_id'] = $typeId;
        }
        if (!empty($brandId)) {
            $where['a.brand_id'] = $brandId;
        }
        if (!empty($num)) {
            $where['a.stock'] = ['>=', $num];
        }
        if(!empty($smallTypeId)){
            $where['a.small_type_id'] = $smallTypeId;
        }
        if(!empty($smallTypeId)){
            $where['a.stock'] = ['>=', $num];
        }
        return $where;
    }
    /**
     * 组装产品搜索查询条件
     * @param int $cateId
     * @param int $typeId
     * @param int $brandId
     * @param int $num
     * @param int $smallTypeId
     * @return array
     */
    protected static function setWhere($cateId, $typeId, $brandId,$smallTypeId,$num) {
        $where = [];
        if (!empty($cateId)) {
            $where['b.category_id'] = $cateId;
        }
        if (!empty($typeId)) {
            $where['b.type_id'] = $typeId;
        }
        if (!empty($brandId)) {
            $where['b.brand_id'] = $brandId;
        }
        if(!empty($smallTypeId)){
            $where['b.small_type_id'] = $smallTypeId;
        }
        if (!empty($num)) {
            $where['b.stock'] = ['>=', $num];
        }
        return $where;
    }

    /**
     * 创建订单并插入数据库
     * @param array $arr
     * @return boolean
     */
    protected static function createOrderData($arr) {
        try {
            $user = self::isLogin($arr['user_id']);
            $rate = config('config.tax');//增值税比例
            //遍历购物车中的每个供应商
            foreach ($arr['goods'] as $k => $v) {
                //查看当前供应商是否有活动
                $discount = Db::name('discount')->where(['supplier_id' => $v['supplier_id']])->find();
                //组装订单信息
                $order[] = self::getOrderData($v, $discount, $user,$rate);
            }
            //订单数据插入数据库
            $result = self::createOrder($order);
        } catch (\Exception $ex) {
            $result = FALSE;
        }
        return $result;
    }

    /**
     * 向数据库插入订单数据
     * @param array $order
     * @return boolean
     */
    protected static function createOrder($order) {
        try {
            Db::startTrans();
            $product = [];
            foreach ($order as $k => $v) {
                // 1.添加订单
                $orderId = Db::name('order')->strict(false)->insertGetId($v);
                // 2.向订单商品数据添加订单id
                foreach ($order[$k]['info'] as $key => $val) {
                    $order[$k]['info'][$key]['order_id'] = $orderId;
                    if (array_key_exists($val['product_id'], $product)) {
                        $product[$val['product_id']] += $val['num'];
                    } else {
                        $product[$val['product_id']] = $val['num'];
                    }
                    ksort($order[$k]['info'][$key]);
                }
                // 3.添加订单商品数据
                $goods = Db::name('order_info')->strict(false)->insertAll($order[$k]['info']);
                // 4.商品数据递减
                foreach ($product as $id => $num) {
                    $dec = Db::name('product')->where(['id' => $id])->setDec('stock', $num);
                }
            }
            if ($orderId && $goods && $dec) {
                $res = $order;
                Db::commit();
            } else {
                $res = false;
                Db::rollback();
            }
        } catch (\Exception $ex) {
            $res = false;
        }
        return $res;
    }

    /**
     * 组装订单信息(商户满减满送活动以及增值税结算)
     * @param array $v
     * @param array $discount
     * @param array $user
     * @param float $rate 增值税比例
     * @return array
     */
    protected static function getOrderData($v, $discount, $user,$rate) {
        try {
            switch ($discount['type']) {
                case 1:
                    //满减活动
                    $order = self::decMoney($v, $discount, $user,$rate);
                    break;
                case 2:
                    //满送活动
                    $order = self::decProduct($v, $discount, $user,$rate);
                    break;
                default :
                    //无活动
                    $order = self::noDiscount($v, $user,$rate);
            }
        } catch (\Exception $ex) {
            $order = [];
        }
        return $order;
    }

    /**
     * 满减活动订单处理
     * @param array $arr 商品信息
     * @param array $rule 活动规则
     * @param array $user 用户信息
     * @param float $rate 增值税比例
     * @return array 订单信息
     */
    protected static function decMoney($arr, $rule, $user,$rate) {
        try {
            // 1.计算订单总价
            $total = 0;
            foreach ($arr['info'] as $k => $v) {
                $arr['info'][$k]['is_give'] = 0;
                $arr['info'][$k]['num'] = $v['specification_name'] * $v['packing_proportion']; //计算商品购买量
                $arr['info'][$k]['tax'] = ('1' == $v['is_include_tax']) ? 0 : $v['price']*$v['packing_proportion']*$rate;//计算商品税收金额
                $total += $v['price'] * $v['packing_proportion']+$arr['info'][$k]['tax'];
                unset($arr['info'][$k]['is_include_tax']);
            }
            // 2.根据活动规则计算(减)金额
            $step = floor($total / $rule['condition_money']);
            //订单消耗的库存
            $dec = $rule['relief_money'] * $step;
            //订单数据组装
            $order['order_no'] = createOrderNo();
            $order['money'] = $total;
            $order['supplier_id'] = $arr['supplier_id'];
            $order['add_time'] = getTime();
            $order['status'] = 0;
            $order['discountmoney'] = $dec;
            $order['remark'] = $arr['remark'];
            $order['paymoney'] = $total - $dec;
            $order['user_id'] = $user['id'];
            $order['addr'] = $user['addr'];
            $order['send_time'] = $arr['send_time']; //获取配送时间
            $order['info'] = $arr['info'];
        } catch (\Exception $ex) {
            $order = [];
        }
        return $order;
    }

    /**
     * 满送活动订单处理
     * @param array $arr 订单数据
     * @param array $rule 活动规则
     * @param array $user 用户数据
     * @param float $rate 增值税比例
     * @return array 订单信息
     */
    protected static function decProduct($arr, $rule, $user,$rate) {
        try {
            // 1.计算订单总价
            $total = 0;
            foreach ($arr['info'] as $k => $v) {
                $arr['info'][$k]['is_give'] = 0;
                $arr['info'][$k]['num'] = $v['specification_name'] * $v['packing_proportion']; //计算商品购买量
                $arr['info'][$k]['tax'] = ('1' == $v['is_include_tax']) ? 0 : $v['price']*$v['packing_proportion']*$rate;//计算商品税收金额
                $total += $v['price'] * $v['packing_proportion']+$arr['info'][$k]['tax'];
                unset($arr['info'][$k]['is_include_tax']);
            }
            // 2.根据优惠规则的id获取送的商品
            $newRule = Db::name('discount')->alias('a')
                    ->join('product_give b', 'a.id=b.discount_id', 'left')
                    ->join('product c', 'b.product_id=c.id', 'left')
                    ->where(['a.id' => $rule['id']])
                    ->field('a.*,b.count,c.name as product_name,c.id as product_id')
                    ->find();
            // 3.根据规则计算送的商品数量
            $step = floor($total / $newRule['condition_money']);
            $brr['product_id'] = $newRule['product_id'];
            $brr['specification_name'] = $newRule['count'];
            $brr['num'] = $step * $newRule['count'];
            $brr['price'] = 0;
            $brr['is_give'] = 1;
            $brr['packing_proportion'] = $step;
            $brr['tax'] = 0;
            $order['order_no'] = createOrderNo();
            $order['money'] = $total;
            $order['supplier_id'] = $arr['supplier_id'];
            $order['add_time'] = getTime();
            $order['status'] = 0;
            $order['discountmoney'] = 0;
            $order['remark'] = $arr['remark'];
            $order['paymoney'] = $total;
            $order['user_id'] = $user['id'];
            $order['addr'] = $user['addr'];
            $order['send_time'] = $arr['send_time']; //获取配送时间
            $arr['info'][] = $brr;
            $order['info'] = $arr['info'];
        } catch (\Exception $ex) {
            $order = [];
        }
        return $order;
    }

    /**
     * 无活动的订单处理
     * @param array $arr 订单数据
     * @param array $user 用户数据
     * @param float $rate 增值税比例
     * @return array 订单信息
     */
    protected static function noDiscount($arr, $user,$rate) {
        try {
            // 1.计算订单总价
            $total = 0;
            foreach ($arr['info'] as $k => $v) {
                $arr['info'][$k]['is_give'] = 0;
                $arr['info'][$k]['num'] = $v['specification_name'] * $v['packing_proportion']; //计算商品购买量
                $arr['info'][$k]['tax'] = ('1' == $v['is_include_tax']) ? 0 : $v['price']*$v['packing_proportion']*$rate;//计算商品税收金额
                $total += $v['price'] * $v['packing_proportion']+$arr['info'][$k]['tax'];
                unset($arr['info'][$k]['is_include_tax']);
            }
            // 2.创建订单数据
            $order['order_no'] = createOrderNo();
            $order['money'] = $total;
            $order['supplier_id'] = $arr['supplier_id'];
            $order['add_time'] = getTime();
            $order['status'] = 0;
            $order['discountmoney'] = 0;
            $order['remark'] = $arr['remark'];
            $order['paymoney'] = $total;
            $order['user_id'] = $user['id'];
            $order['addr'] = $user['addr'];
            $order['send_time'] = $arr['send_time']; //获取配送时间
            $order['info'] = $arr['info'];
        } catch (\Exception $ex) {
            $order = [];
        }
        return $order;
    }

    /**
     * 判断用户是否登录，已登录则返回用户信息
     * @return type
     */
    protected static function isLogin($user_id = '') {
        if (empty($user_id)) {
            $user_id = input('user_id');
        }
        $user = Db::name('user')->where(['id' => $user_id])->find();
        if (false != $user) {
            return $user;
        } else {
            $res = config('code.logout');
            return jsonReturn($res['status'], $res['msg'], []);
        }
    }

    /**
     * 对象转换为数组
     * @param object $object
     * @return array
     */
    protected static function objectToArray(&$object) {
        if (is_object($object)) {
            $arr = (array) ($object);
        } else {
            $arr = &$object;
        }
        if (is_array($arr)) {
            foreach ($arr as $varName => $varValue) {
                $arr[$varName] = self::objectToArray($varValue);
            }
        }
        return $arr;
    }

}
